//
//  XQLocationTool.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/3.
//

import UIKit
import CoreLocation

let kXQShowAlertDate = "kXQShowAlertDate"

class XQLocationTool: NSObject {

    static func checkLocationAuthorization(controller : UIViewController) {
        
        let locationManager = CLLocationManager()
        
        if (locationManager.authorizationStatus == .denied) {
            let needPop = XQInitManager.shared.popLocation()
            if (needPop && checkCurrentTimeNeedPopAlert()) {
                DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                    XQAlertManager.showDeniedAccessPopAlert(on: topViewController()!, message: "To offer you personalized loan options and services in your area, we need access to your location. Please enable location services for a tailored experience.")
                }
            }
        }
    }
    
    static func checkCurrentTimeNeedPopAlert() -> Bool {
        let defaults = UserDefaults.standard
        
        if let latestAlertDate = defaults.object(forKey: kXQShowAlertDate) as? Date {
            let nowD = Date()
            let aboveOneDay = latestAlertDate.addingTimeInterval(24 * 3600)
            
            if (nowD > aboveOneDay) {
                defaults.set(nowD, forKey: kXQShowAlertDate)
                defaults.synchronize()
                return true
            }else {
                return false
            }
        }else {
            let nowD = Date()
            defaults.set(nowD, forKey: kXQShowAlertDate)
            defaults.synchronize()
            return true
        }
    }
    
    static func topViewController() -> UIViewController? {
        guard let windowScene = UIApplication.shared.connectedScenes
                .filter({ $0 is UIWindowScene })
                .first as? UIWindowScene else {
            return nil
        }
        
        let rootViewController = windowScene.windows.first?.rootViewController
        return getTopViewController(from: rootViewController)
    }
    
    private class func getTopViewController(from viewController: UIViewController?) -> UIViewController? {
        if let navigationController = viewController as? UINavigationController {
            return getTopViewController(from: navigationController.visibleViewController)
        } else if let tabBarController = viewController as? UITabBarController {
            return getTopViewController(from: tabBarController.selectedViewController)
        } else if let presentedViewController = viewController?.presentedViewController {
            return getTopViewController(from: presentedViewController)
        } else {
            return viewController
        }
    }
}
